<template>
  <div>
    <div><h1>订单列表</h1></div>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="输入商品名称/关键字/ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.statusId"
            placeholder="请选择订单状态"
            clearable
            style="width: 160px"
          >
            <el-option label="待支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="已发货" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select
            v-model="searchForm.typeId"
            placeholder="请选择订单类型"
            clearable
            style="width: 160px"
          >
            <el-option
              v-for="item in OrderTypeList"
              :label="item.dictName"
              :value="item.dictValue"
              :key="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">搜索</el-button>
          <el-button type="primary" @click="OnAddOrder">添加订单</el-button>
          <el-button type="success" @click="OnExpartOrder">导出订单</el-button>
          <el-button type="danger" @click="OnDeleteBatch">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="OrderList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderId" label="ID" width="50" />
        <el-table-column prop="orderNo" label="订单编号" width="100" />
        <el-table-column prop="prodInfo" label="商品信息" width="180" />
        <el-table-column prop="orderAmount" label="订单总金额" width="100" />
        <el-table-column
          prop="orderType"
          label="订单类型"
          width="100"
          :formatter="formatter"
        />
        <el-table-column prop="createTime" label="创建时间" width="120" />
        <el-table-column prop="createBy" label="消费者" width="100" />
        <el-table-column prop="imageList" label="商品图片" width="160">
          <template #default="scope">
            <el-image
              v-if="scope.row.imageList != null && scope.row.imageList != ''"
              v-for="item in scope.row.imageList"
              :src="item"
              :key="item"
              style="width: 50; height: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="商品信息" width="100">
          <template #default="scope">
            <el-tag type="priamry" v-if="scope.row.orderStatus == 0"
              >未支付</el-tag
            >
            <el-tag type="success" v-if="scope.row.orderStatus == 1"
              >已支付</el-tag
            >
            <el-tag type="danger" v-if="scope.row.orderStatus == 2"
              >待支付</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="HandlerInfoOrder(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加订单" width="700">
        <el-form :model="orderForm">
          <el-form-item
            label="请选择要购买的商品"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="orderForm.infoId"
              placeholder="请选择要购买的商品"
            >
              <el-option
                v-for="item in ProdInfoList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="输入购买数量" :label-width="formLabelWidth">
            <el-input v-model="orderForm.buyNum" autocomplete="off" />
          </el-form-item>
          <div>
            <el-button type="primary" @click="OnAddProdInfo">添加</el-button>
          </div>
          <div>
            <el-table :data="buyInfoList" stripe style="width: 100%">
              <el-table-column prop="prodId" label="商品ID" width="100" />
              <el-table-column prop="prodName" label="商品名称" width="120" />
              <el-table-column prop="prodPrice" label="商品价格" width="120" />
              <el-table-column prop="buyNum" label="购买数量" width="120" />
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="OnDeleteProdInfor(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div>总价：{{ totalAmount }}元</div>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="OnsubmitAddOrder">
              添加订单
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  GetOrderList,
  getProdInfoList,
  addOrder,
  getDictList,
  deleteOrderBatch,
} from "../api/api";
import { onMounted, reactive, ref } from "vue";
import { ElMessageBox } from "element-plus";
import lifecycle from "echarts/types/src/core/lifecycle.js";
const OrderList = ref([]);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
  statusId: null,
  typeId: null,
});
const total = ref(0);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const orderForm = ref({
  infoId: null,
  buyNum: 1,
});

const ProdInfoList = ref([]);
const buyInfoList = ref([]);
const totalAmount = ref(0);
const OrderTypeList = ref([]);
const multipleSelection = ref<any[]>([]);

const userId = ref(0);

//批量删除
const OnDeleteBatch = () => {
  ElMessageBox.confirm("数据删除后将无法恢复确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let ids: any = [];
      multipleSelection.value.forEach((item) => {
        ids.push(item.orderId);
      });
      deleteOrderBatch(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//多选变量
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//导出订单列表
const OnExpartOrder = () => {
  let url = "http://localhost:9011/shop/order/exportOrderList/" + userId.value;
  window.open(url);
};

//数据转换
const formatter = (row: any) => {
  let name = "";
  OrderTypeList.value.forEach((item) => {
    if (item.dictValue === row.orderType) {
      name = item.dictName;
    }
  });
  return name;
};

//订单详情

const HandlerInfoOrder = (row: any) => {
  console.log("添加订单详情", row);
};

//添加订单接口

const OnsubmitAddOrder = () => {
  addOrder(buyInfoList.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加订单成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//删除购物车商品
const OnDeleteProdInfor = (row: any) => {
  buyInfoList.value.forEach((item, index) => {
    if (item.infoId == row.infoId) {
      buyInfoList.value.splice(index, 1);
    }
  });

  //动态计算总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    console.log(item, "------");
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};

//添加商品到购物车
const OnAddProdInfo = () => {
  //添加购物车商品
  ProdInfoList.value.forEach((item) => {
    if (item.infoId === orderForm.value.infoId) {
      item.buyNum = orderForm.value.buyNum;
      buyInfoList.value.push(item);
    }
  });
  //动态计算总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
  console.log(totalAmount, "-------------");
};

//新增订单
const OnAddOrder = () => {
  orderForm.value = {
    infoId: null,
    buyNum: 1,
  };
  buyInfoList.value = [];
  totalAmount.value = 0.0;
  dialogFormVisible.value = true;
};

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};

//分页订单列表
const loadList = () => {
  GetOrderList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      OrderList.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadList();
  //获取商品信息列表
  getProdInfoList().then((res) => {
    if (res.data.code == 200) {
      ProdInfoList.value = res.data.data;
      console.log(ProdInfoList.value, "---------");
    }
  });
  //获取订单状态类表OrderTypeList
  getDictList(4).then((res) => {
    if (res.data.code == 200) {
      OrderTypeList.value = res.data.data;
    }
  });

  //获取用户ID
  let u = sessionStorage.getItem("user");
  let user1 = JSON.parse(u);
  userId.value = user1.userId;
});
</script>

<style scoped></style>
